// 校验登录状态
checklogin()
// 页面数据的渲染
renderUserName()
getData()
// 退出登录
document.querySelector('#logout').addEventListener('click', function () {
    // 删除token
    localStorage.removeItem('token')
    // 跳转登录
    location.href = './login.html'
})
// 1.更新用户名
function renderUserName() {
    const username = localStorage.getItem('username')
    document.querySelector('.username').innerHTML = username
}
// 2.更新预览卡片
// 2.1获取看板所有的数据
async function getData() {
    const token = localStorage.getItem('token')
    // 避免页面提示两次，如果没有token等待校验函数退出即可
    if (!token) return
    // 1.获取数据
    // 1.1调用接口
    const res = await axios({ url: '/dashboard' })
    // 2.渲染overview数据
    renderOverview(res.data.overview)
    // 渲染图表数据
    // rendeerLine(res.data.year)
    // renderPie(res.data.salaryData)
    // // groupData是对象
    // renderBar(res.data.groupData)
    // renderDoublePie(res.data.salaryData)
    // renderMap(res.data.provinceData)
    // console.log(res.data.salaryData);
    // echarts图表渲染
    let lineChart=rendeerLine(res.data.year)
    let pieChart=renderPie(res.data.salaryData)
    let barChart=renderBar(res.data.groupData)
    let doublepieChart= renderDoublePie(res.data.salaryData)
    let mapChart= renderMap(res.data.provinceData)
    // 通过闭包来解决自适应问题（用闭包解决图表resize问题）
    window.addEventListener('resize',function(){
        // 需要各个图标
        lineChart()
        pieChart()
        barChart()
        doublepieChart()
        mapChart()
    })

}
// 2.2更新预览卡片 更新看板所有的数据
function renderOverview(data) {
    console.log(data);
    for (let k in data) {
        if (k === 'age') {
            document.querySelector(`.${k}`).innerHTML = data[k].toFixed(2)
        }
        else { document.querySelector(`.${k}`).innerHTML = data[k] }

    }
}
// 插入折线图图标
function rendeerLine(data) {
    // 实例化图标
    const myChart = echarts.init(document.querySelector('#line'));
    // option
    const option = {
        title: {
            text: '2022全学科薪资走势',
            left: 20,
            top: 10
        }
        ,
        tooltip: {},
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: data.map(item => item.month)
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 25000,
            interval: 5000,
            axisLabel: {
                formatter: '{value}'
            }
        },
        series: [
            {
                name: 'Salary',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                // Increase the size of the symbol (data points)
                symbolSize: 10, // Adjust this value to change the size of the data points
                lineStyle: {
                    width: 4,// Adjust this value to change the line thickness
                    color: 'rgba(68, 137, 255, 1)',

                },
                itemStyle: {
                    borderColor: 'rgba(68, 137, 255, 1)', // 设置空心圆边框的颜色为蓝色
                    borderWidth: 2, // 设置空心圆边框的宽度,
                    color: '#fff'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [{
                            offset: 0,
                            color: 'rgba(68, 137, 255, 0.3)'
                        }, {
                            offset: 1,
                            color: 'rgba(68, 137, 255, 0)'
                        }]
                    )
                },
                data: data.map(item => item.salary)
            }
        ]
    };
    // 图表应用配置项
    myChart.setOption(option)
    // 返回一个函数 通过闭包来设置自适应问题
    return function(){
        myChart.resize()
    }
}
// 插入饼图图表
function renderPie(data) {
    // 实例化
    const myChart = echarts.init(document.querySelector('#salary'))
    const option = {
        title: {
            text: '班级薪资分布',
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'horizontal',
            bottom: '5%',
            data: data.map(item => item.label)
        },
        series: [
            {
                name: '薪资分布',
                type: 'pie',
                radius: ['40%', '60%'], // 减小内外半径的差值，使圆环变窄
                center: ['50%', '50%'], // 设置饼图中心位置
                itemStyle: {
                    borderRadius: 10, // 设置圆角
                    borderColor: '#fff', // 设置边框颜色
                    borderWidth: 2 // 设置边框宽度
                },
                label: {
                    show: false,// 隐藏标签
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        position: 'center',
                        fontSize: 40,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false // 隐藏标签线
                },
                data: data.map(item => {
                    return { value: item.g_count + item.b_count, name: item.label }
                }, [])

            }
        ]
    };
    myChart.setOption(option)
    return function(){
        myChart.resize()
    }
}
// 插入柱状图
function renderBar(data) {
    const myChart = echarts.init(document.querySelector('#lines'))
    const btns = document.querySelector('#btns')
    //    先对一条对象进行分割 将它们的属性都放到数组里面
    // 默认是第一条数据
    let xarr = data[1].map(item => item.name)
    let harr = data[1].map(item => item.hope_salary)
    let sarr = data[1].map(item => item.salary)
    btns.addEventListener('click', function (e) {
        if (e.target.tagName === 'BUTTON') {
            // 1. 清楚全亮
            document.querySelector('.btn-blue').classList.remove('btn-blue')
            // 2.点亮小圆点
            e.target.classList.add('btn-blue')
            //  3. 对对象里面每条数组进行渲染
            // 3.1 修改数据 
            xarr = data[Number(e.target.textContent)].map(item => item.name)
            harr = data[Number(e.target.textContent)].map(item => item.hope_salary)
            sarr = data[Number(e.target.textContent)].map(item => item.salary)
            // 3.2 对数据进行渲染
            // option={xAxis:{data:xarr}}
            myChart.setOption({
                xAxis: { data: xarr },
                series: [{ data: harr }, { data: sarr }]

            })
            // console.log({data: harr},{data: sarr});

        }
    })
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        xAxis: {
            type: 'category',
            data: xarr
        },
        series: [
            {
                name: '期望工资',
                type: 'bar',
                data: harr,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [{ offset: 0, color: 'rgb(0, 176, 155)' }, // 深绿色 起始位置
                        { offset: 1, color: '#fff' } // 浅绿色 结束位置

                        ]
                    )
                }
            },
            {
                name: '实际工资',
                type: 'bar',
                data: sarr,
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(
                        0, 0, 0, 1,
                        [
                            { offset: 0, color: '#1E90FF' }, // 深蓝色 起始位置
                            { offset: 1, color: '#fff' } // 浅蓝色 结束位置

                        ]
                    )
                }
            }
        ]
    };
    myChart.setOption(option)
    return function(){
        myChart.resize()
    }
}
// 插入双饼图
function renderDoublePie(data) {
    const myChart = echarts.init(document.querySelector('#gender'));

    // 构建两个数据集，分别用于男生和女生
    const datas = [
        data.map(item => ({ name: item.label, value: item.b_count })),
        data.map(item => ({ name: item.label, value: item.g_count }))
    ];

    const option = {
        title: {
            text: '男女薪资分布',
            left: 'center',
            top: '10%',
            textStyle: {
                color: 'rgba(0, 0, 0, 0.6)',
                fontWeight: 'normal',
                fontSize: 14
            }
        },
        series: [
            {
                name: '男生',
                type: 'pie',
                radius: [40, 60],
                center: ['50%', '30%'], // 第一个饼图的位置 更靠上一些
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: 1
                },
                label: {
                    alignTo: 'edge',
                    formatter: '{name|{b}}\n{value|{c} }',
                    minMargin: 5,
                    edgeDistance: 10,
                    lineHeight: 15,
                    rich: {
                        time: {
                            fontSize: 10,
                            color: '#999'
                        }
                    }
                },
                labelLine: {
                    length: 15,
                    length2: 0,
                    maxSurfaceAngle: 80
                },
                data: datas[0],
            },
            {
                name: '女生',
                type: 'pie',
                radius: [40, 60],
                center: ['50%', '70%'], // 第二个饼图的位置，更靠下一些
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: 1
                },
                label: {
                    alignTo: 'edge',
                    formatter: '{name|{b}}\n{value|{c}}',
                    minMargin: 5,
                    edgeDistance: 10,
                    lineHeight: 15,
                    rich: {
                        time: {
                            fontSize: 10,
                            color: '#999'
                        }
                    }
                },
                labelLine: {
                    length: 15,
                    length2: 0,
                    maxSurfaceAngle: 80
                },
                data:datas[1]
            }
        ]
    };

    // 绘制图表
    myChart.setOption(option);
    return function(){
        myChart.resize()
    }
}
// 插入地图
function renderMap(data) {
    const myChart = echarts.init(document.querySelector('#map'))
    function mapTooltipClick(name) {
        alert(name)
    }
    
    function tooltipCharts() {
        console.log(arguments[0]);
        var myChart1 = echarts.init(document.getElementById('tooltipBarId'));
        var option = {
            tooltip: {},
            dataset: {
                source: [
                    ['xAxis', '201701', '201702', '201703', '201704', '201705', '201706', '201707', '201708', '201709', '20170', '201710', '20170', '201801'],
                    ['amount', 41.1, 30.4, 65.1, 53.3, 83.8, 98.7, 65.1, 53.3, 41.1, 30.4, 53.3, 41.1, 53.3, 83.8]
                ]
            },
            xAxis: {
                type: 'category',
                interval: true,
                axisLabel: {
                    rotate: 45
                },
                axisTick: {
                    show: false
                }
            },
            yAxis: {},
            color: ['#4FA8F9', '#F5A623'],
            grid: {
                show: true,
                backgroundColor: '#FAFAFA',
                left: 30,
                right: 20,
                top: 20
            },
            series: [{
                type: 'bar',
                smooth: true,
                seriesLayoutBy: 'row',
                barWidth: 10
            }]
        };
        myChart1.setOption(option);
    }
    option = {
        visualMap: {
            min: 0,
            max: 1000,
            left: 'left',
            top: 'bottom',
            text: ['高', '低'],
            calculable: false,
            orient: 'horizontal',
            inRange: {
                color: ['#e0ffff', '#006edd'],
                symbolSize: [30, 100]
            }
        },
        tooltip: {
            padding:8,
            enterable: true,
            transitionDuration: 1,
            textStyle: {
                color: '#fff',
                decoration: 'none',
            }
        },
        series: [{
            type: 'map',
            mapType: 'china',
            itemStyle: {
                normal: {
                    label: {
                        show: false
                    }
                },
                emphasis: {
                    label: {
                        show: true
                    }
                }
            },
            label: {
                normal: { //静态的时候展示样式
                    show: true, //是否显示地图省份得名称
                    textStyle: {
                        color: "#fff",
                        fontSize: 12
                    }
                },
                emphasis: { //动态展示的样式
                    color: '#fff',
                },
            },
            data: [{
                    name: '北京',
                    value: 0
                },
                {
                    name: '天津',
                    value: 0
                },
                {
                    name: '上海',
                    value: 0
                },
                {
                    name: '重庆',
                    value: 0
                },
                {
                    name: '河北',
                    value: 0
                },
                {
                    name: '河南',
                    value: 0
                },
                {
                    name: '云南',
                    value: 0
                },
                {
                    name: '辽宁',
                    value: 0
                },
                {
                    name: '黑龙江',
                    value: 0
                },
                {
                    name: '湖南',
                    value: 0
                },
                {
                    name: '安徽',
                    value: 0
                },
                {
                    name: '山东',
                    value: 0
                },
                {
                    name: '新疆',
                    value: 0
                },
                {
                    name: '江苏',
                    value: 0
                },
                {
                    name: '浙江',
                    value: 0
                },
                {
                    name: '江西',
                    value: 0
                },
                {
                    name: '湖北',
                    value: 0
                },
                {
                    name: '广西',
                    value: 0
                },
                {
                    name: '甘肃',
                    value: 0
                },
                {
                    name: '山西',
                    value: 0
                },
                {
                    name: '内蒙古',
                    value: 0
                },
                {
                    name: '陕西',
                    value: 0
                },
                {
                    name: '吉林',
                    value: 0
                },
                {
                    name: '福建',
                    value: 0
                },
                {
                    name: '贵州',
                    value: 0
                },
                {
                    name: '广东',
                    value: 0
                },
                {
                    name: '青海',
                    value: 0
                },
                {
                    name: '西藏',
                    value: 0
                },
                {
                    name: '四川',
                    value: 0
                },
                {
                    name: '宁夏',
                    value: 0
                },
                {
                    name: '海南',
                    value: 0
                },
                {
                    name: '台湾',
                    value: 0
                },
                {
                    name: '香港',
                    value: 0
                },
                {
                    name: '澳门',
                    value: 0
                },
            ]
        }, ]
    }
    var count = 0;
    var timeTicket = null;
    var dataLength = option.series[0].data.length;
    timeTicket && clearInterval(timeTicket);
    timeTicket = setInterval(function() {
        myChart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
        });
        myChart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: (count) % dataLength
        });
        myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: (count) % dataLength
        });
        count++;
    }, 1000);
    
    myChart.on('mouseover', function(params) {
        console.log(params)
        clearInterval(timeTicket);
        myChart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0
        });
        myChart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: params.dataIndex
        });
        myChart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: params.dataIndex,
        });
    });
    myChart.on('mouseout', function(params) {
        timeTicket && clearInterval(timeTicket);
        timeTicket = setInterval(function() {
            myChart.dispatchAction({
                type: 'downplay',
                seriesIndex: 0,
            });
            myChart.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: (count) % dataLength
            });
            myChart.dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: (count) % dataLength
            });
            count++;
        }, 1000);
    });
    
    myChart.setOption(option)
        // 根据接口数据，修改option中的series的data
        const newData=option.series[0].data.map(item=>{
            // item是初始化地图数据的每一项
            // item在接口数据中查找
            const city=data.find(city=>{
                return city.name.includes(item.name)
            })
            return {
                name:item.name,
                value:city?city.value:0
            }
        })
    return function(){
        myChart.resize()
    }
}
